package com.blackink.controller;

import com.blackink.tool.RandomString;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class FileController {

    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file){
        try {
            if (file.isEmpty()){
                return "file is empty";
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("文件名"+fileName+"文件后缀"+suffixName);
            Date date = new Date();
            SimpleDateFormat format =new SimpleDateFormat("YYMMddHHmmss");
            String randomFileName = format.format(date)+RandomString.getRandomSalt();
            String filePath = "D:\\demoDownloads\\";
            String path = filePath+randomFileName;
            File dest = new File(path);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "faliure";
    }

    @ResponseBody
    @RequestMapping(value = "/download")
    public String download(HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            File file = new File("D:\\demoDownloads\\新建文本文档.txt");
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            response.setContentType("application/force-download");
            response.addHeader("Content-disposition", "attachment;fileName=" + "demo.txt");
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int i = bis.read(buf);
            while(i != -1) {
                os.write(buf, 0,buf.length);
                os.flush();
                i = bis.read(buf);
            }
            return "success";
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            fis.close();
            bis.close();

        }
        return "faliure";
    }

    @RequestMapping("/updow")
    public String demo(){
        return "updow";
    }
}
